package dao;

import org.springframework.stereotype.Component;
import pojo.User;
import util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @ Author     ：LILA3
 * @ Date       ：Created in 4:37 PM 7/24/2018
 */
@Component
public class UserDao {
    Connection connection = DBUtil.getConnection();

    public UserDao() {
        System.out.println(UserDao.class.getName());
    }

    public int insert(User user) throws Exception {
        String sql = "insert into spring_users(name,password,age) values(?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, user.getName());
        statement.setString(2, user.getPassword());
        statement.setInt(3, user.getAge());
        return statement.executeUpdate();
    }

    public User findByName(String name) throws Exception {
        String sql = "select * from SPRING_USERS where name = '" + name + "'";
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet rs = statement.executeQuery();
        User user = null;
        while (rs.next()) {
            user = new User();
            user.setName(rs.getString("name"));
            user.setPassword(rs.getString("password"));
            user.setAge(rs.getInt("age"));
        }
        return user;
    }

}
